import {Component, OnInit} from '@angular/core';
import {MsgResult} from '../../../../models/msg-result';
import {MsgConstants} from '../../../../constants/constants';
import {ResponseUtil} from '../../../../util/response-util';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {SlagService} from './slag.service';
import {Message} from "@stomp/stompjs";
import {StompService} from "@stomp/ng2-stompjs";
import {Observable} from "rxjs/Observable";
import {Subscription} from "rxjs/Subscription";
import {stompConfig} from "../../../../constants/stompConfig";

declare var $;
declare var moment;
declare var BMap;
declare var mapv;
declare var BMapLib;
declare var echarts;
declare var BMAP_DRAWING_POLYGON;
declare var INFOBOX_AT_TOP;

@Component({
  selector: 'app-slag',
  templateUrl: './slag.component.html'
})
export class SlagComponent  implements OnInit {

  map;
  trafficCtrl;
  lastInfo;
  table;
  treeObj;
  loadSetInterval;
  mapvLayer;

  administrative: any = '';

  nullSiteList: string = '正在加载';
  selectorPointType: string = 'allNationalSite';
  mapType: string = 'map';
  trackDeviceType:　string = '0';
  trackType: string = 'real';
  trackDeviceCode: string = '';
  trackSearchDate: string = '';
  selectDate:　string = '';
  isLoading: boolean = false;
  isNormalMap: boolean = true;
  isTraffic: boolean = false;


  dateArray: Array<any> = [];
  trackHistoryArr: Array<any> = [];
  trackRealArr: Array<any> = [];
  lushuOverlays: Array<any> = [];  // 路书 索引
  lushuData: Array<any> = [];  // 路书 对象
  lushuLine: Array<any> = [];  // 路书 线
  lushuSpotrIcon: Array<any> = []; // 路书 车
  lushuClickElem;

  activeSiteCode: string = '';
  deviceType: string = '0';
  deviceStatus:  string = '';
  regionCode: string = '';
  nullCarDataContent: string = '';

  carSearchArr: Array<any> = [];

  carTypeArr : Array<any> = [];
  carStatusArr : Array<any> = [];
  carRealInfo : Array<any> = [];
  carRealCacheInfo : Array<any> = [];
  lastRegionAreaOverlay;

  carSearchCode: string;
  regionDataArr: Array<any> = [];

  loadDataIndex: number = 1;
  loadDataNumber: number = 300;
  loadDataTime: number = 100;
  radius: number = 3000;
  clickPoint = {lat : '', lng : ''};

  // Stream of messages
  private subscription: Subscription;
  private ngSubscription: Subscription;
  public messages: Observable<Message>;
  noAckMessages: Array<Message> = [];

  // Subscription status
  public subscribed: boolean;

  // Array of historic message (bodies)
  public mq: Array<any> = [];

  // A count of messages received
  public count = 0;

  private _counter = 1;

  private slagStomp: any;

  constructor(
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private slagService: SlagService,
  ) {
    this.slagStomp = new StompService(stompConfig)
  }

  ngOnInit() {
    this.initMap();
    this.initMapContentData();
    this.screenChange();
    this.initHistoryDate();
    this.getCarType();
    this.getCarStatus();
    this.getCarRealPoint();
    // this.getCarRealAreaPoint();
    this.getRegionData();
    this.trafficControl();
    // this.inintRetractionAnimation();
    this.subscribe();
  }

  ngOnDestroy() {
    this.unsubscribe();
  }

  /**
   * 初始化地图
   */
  initMap() {
    $('#realTimeMap').css('height', window.innerHeight - 50 + 'px');
    $('.one-notbreadcrumb').css('height',window.innerHeight-50+'px');
    this.map = new BMap.Map('realTimeMap', {enableMapClick: false, minZoom: 5, maxZoom: 18});
    let centerPoint = new BMap.Point(113.658221, 34.780377);  // 创建点坐标
    this.map.centerAndZoom(centerPoint, 12);
    // 地图样式
    let mapStyle =[
      {
        'featureType': 'land',
        'elementType': 'geometry',
        'stylers': {
          'color': '#e7f7fc'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'all',
        'stylers': {
          'color': '#96b5d6'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'all',
        'stylers': {
          'color': '#b0d3dd'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#d1c6a6'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#e6d9ab'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#cccccc'
        }
      },
      {
        'featureType': 'local',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#b6c6de'
        }
      },
      {
        'featureType': 'subway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#cddbd2'
        }
      },
      {
        'featureType': 'land',
        'elementType': 'all',
        'stylers': {
          'color': '#edf1f5'
        }
      },
      {
        'featureType': 'administrative',
        'elementType': 'geometry',
        'stylers': {
          'color': '#a7c8ec'
        }
      },
      {
        'featureType': 'railway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      }
    ]//白底
    this.map.setMapStyle({styleJson: mapStyle});
    this.map.enableScrollWheelZoom();
    this.map.enableDragging();
    this.map.addEventListener('click',(e)=>{
      if(!(e.overlay && e.overlay.hasOwnProperty('content')) && this.lastInfo){
        this.lastInfo.close();
      }
      // if(this.trackType == 'real'){
      //   this.map.clearOverlays();
      //   this.carRealInfo = [];
      //   this.clickPoint = e.point;
      //   let circle3 = new BMap.Circle(e.point,this.radius,{
      //     "strokeColor":"#eea77c",
      //     "strokeWeight":2,
      //     "fillColor":"#eea77c",
      //     "fillOpacity":0.1,
      //   });
      //   this.map.addOverlay(circle3);
      //   this.loadDataIndex = 1;
      //   this.getCarRealAreaPoint();
      // }

      // this.map.removeOverlay(this.lastRegionAreaOverlay);
      // if(this.lastRegionAreaOverlay){
      //   this.map.removeOverlay(this.lastRegionAreaOverlay);
      //   this.map.clearOverlays();
      //   this.carRealInfo = [];
      // }
      // this.lastRegionAreaOverlay = '';
      $('.one-peach-dropdown-menu').each(function(){
        $(this).hide();
      })
    })
  }
  /**
   * 屏幕大小改变
   */
  screenChange(){
    $(window).resize(function(){
      $('#realTimeMap').css('height', window.innerHeight - 50 + 'px');
      $('.one-notbreadcrumb').css('height',window.innerHeight-50+'px');
    });
  }
  initMapContentData() {

  }

  /**
   * 实时数据推送(消息推送)
   * @param result
   */
  public subscribe() {
    console.log('订阅渣土车消息推送');
    if (this.subscribed) {
      return;
    }
    // Stream of messages
    this.messages = this.slagStomp.subscribe('/exchange/movingExchange',stompConfig.noAckHeaders);

    // Subscribe a function to be run on_next message
    this.subscription = this.messages.subscribe(this.on_next);

  }
  /** Consume a message from the _stompService */
  public on_next = (message: Message) => {
    if (this.trackType=='history') {
      return false;
    }
    let acceptData  = JSON.parse(message.body);
    let slagArr = this.carRealCacheInfo.concat(acceptData);
    this.carRealCacheInfo = this.unique(slagArr);
    //  mapv
    this.carRealInfo = this.carRealCacheInfo.slice((this.loadDataIndex-1)*this.loadDataNumber,this.loadDataIndex*this.loadDataNumber);
    this.startSetInterval();
    //mapv
    this.mapvLoad();
  };

  /**
   * 去重
   * @param arr
   * @returns {Array}
   */
  unique(arr){
    let result = [];
    let temp = [];
    arr.forEach((val)=>{
      temp[val.deviceCode] = val;
    });
    for (let code in temp) {
      result.push(temp[code]);
    }
    return result;
  }
  public unsubscribe() {
    console.log('取消消息推送');
    if (!this.subscribed) {
      return;
    }

    // This will internally unsubscribe from Stomp Broker
    // There are two subscriptions - one created explicitly, the other created in the template by use of 'async'
    this.subscription.unsubscribe();
    this.subscription = null;
    this.messages = null;
    this.noAckMessages = null;
    this.mq = null;
    this.subscribed = false;
    this.slagStomp.disconnect();
  }
  /**
   * 默认缩回动画
   */
  inintRetractionAnimation(){
    let elem = $(".one-peach-site-detail");
    let siteDetailHeight = elem.height();
    elem.animate({
      right:"-300px",
      bottom:siteDetailHeight-64+"px"
    },1500,()=>{
      $(".one-peach-site-toggle").removeClass("one-peach-site-toggle").addClass("one-peach-site-toggle-large").animate({
        left:"-74px"
      },500);
    });
    elem.siblings(".one-peach-factorLegend").animate({
      right:"20px"
    },1500);
  }
  /**
   * 隐藏父元素
   */
  closeParent = (elem) =>{
    $(elem).parent().parent().hide();
  };

  /**
   *清除状态及数据
   */
  clearData() {
    this.isLoading = true;
    this.nullSiteList = '正在加载';
    this.trackHistoryArr = [];
    this.trackRealArr = [];
  }

  /**
   *清除所有标注
   */
  clearAllLabel() {
    this.map.clearOverlays();
  }

  /**
   *清除部分标注
   */
  clearPartLabel() {
    if (this.map.getOverlays().length) {
      this.map.getOverlays().forEach((elem, i) => {
        if (elem.content && elem.content.indexOf(this.selectorPointType) != -1) {
          this.map.removeOverlay(elem);
        }
      })
    }
  }

  /**
   * aqi等级
   */
  aqiLevel = (data) => {
    return data <= 50 ? 1
      : data > 50 && data <= 100 ? 2
        : data > 100 && data <= 150 ? 3
          : data > 150 && data <= 200 ? 4
            : data > 200 && data <= 300 ? 5
              : data > 300 ? 6 : 7;
  };


  /**
   *下拉列表点击事件
   */
  dropDownClick(e){
    if($(e.target).siblings('.one-peach-dropdown-menu').css('display') == 'none'){
      $(e.target).siblings('.one-peach-dropdown-menu').show().prev().show().parent().addClass('active');
    }else{
      $(e.target).siblings('.one-peach-dropdown-menu').hide().prev().hide().parent().removeClass('active');
    }
  }
  dropDownHide(e){
    $(e.target).children('.one-peach-dropdown-menu').hide().prev().hide().parent().removeClass('active');
  }
  /**
   * 开始/暂停轮播
   */
  playOrPauseHotInterval(elem){
    if($(elem).find('.fa').hasClass('fa-play')){
      // this.startHotInterval();
      $(elem).find('.fa').removeClass('fa-play').addClass('fa-pause');
    }else{
      $(elem).find('.fa').addClass('fa-play').removeClass('fa-pause');
      // this.stopHotInterval();
    }
  }
  /**
   *添加图表
   */
  siteCountChart(data){
    let count :number = 0;
    let carArr : Array<any> = [];
    this.carTypeArr.forEach((val,i)=>{
      if(data[val.deviceCode]){
        count += data[val.deviceCode];
        carArr.push({value:data[val.deviceCode],name:val.deviceType});
      }
    });
    let siteChart = echarts.init(document.getElementById('one-peach-count-chart'),null, {devicePixelRatio: 3});
    let siteChartOption= {
      title : {
        text:count,
        textStyle:{
          fontSize:30
        },
        subtext: '车辆',
        subtextStyle:{
          fontSize:14
        },
        left:'center',
        top:'center',
        itemGap:3
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params, ticket, callback) {
          return params.name+'<br/>数量：'+params.value+'个<br/>占比：'+params.percent+'%';
        }
      },
      grid:{
        top:10,
        right:10
      },
      color:['#C4E5FB','#588CE0','#86ACEB'],
      series: [ {
        name:'站点数据',
        type:'pie',
        radius: ['70%', '90%'],
        avoidLabelOverlap: false,
        label: {
          normal: {
            show: false,
            position: 'center',
            formatter:function(){

            }
          }
        },
        labelLine: {
          normal: {
            show: false
          }
        },
        data:carArr
      }
      ]
    };
    siteChart.setOption(siteChartOption);
  }


  // 删除路书运动ICON
  deleteLushuIcon() {
    this.lushuSpotrIcon.forEach((sportIcon,i)=>{
      this.map.removeOverlay(sportIcon)
    });
    this.lushuSpotrIcon = [];
  }
  // 清除路书中的所有数据
  clearLushuData(){
    this.map.clearOverlays();
    const presentDataBox = this.trackType === 'real'? $('.trackReal') : $('.trackHistory');
    presentDataBox.find('.choose-btn').next().find('input').each(function(){
      this.checked = false;
    });
    (this.trackType === 'history') && $('.trackHistory .fa-pause').removeClass('fa-pause').addClass('fa-play');
    this.lushuOverlays = [];
    this.lushuData = [];
    this.lushuLine = [];
    this.lushuSpotrIcon = [];
  }
  /**
   * 格式历史轨迹化日期
   */
  initHistoryDate() {
    const config = {
      timePicker: true,
      timePicker24Hour: true,
      locale: {
        format: 'YYYY-MM-DD HH:mm',
        separator: ' 至 ',
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: [ '日', '一', '二', '三', '四', '五', '六'],
        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        firstDay: 1
      },
      dateLimit: {
        days: 1
      },
      autoApply: true,
      opens: "left",
      showDropdowns: true,
      startDate: moment().subtract(1,'d').format('YYYY-MM-DD HH:mm'),
      endDate: moment().format('YYYY-MM-DD HH:mm'),
      maxDate: moment().format('YYYY-MM-DD HH:mm')
    };
    $('#pathDate').daterangepicker(config).on('hide.daterangepicker', ( e ) => {
      if ( this.trackSearchDate == e.target.value || !this.lastRegionAreaOverlay ){
        return false;
      } else {
        this.trackSearchDate = e.target.value;
        this.getCarHistoryPoint();
      }
    });
    this.trackSearchDate = $('#pathDate').val();
  }

  trackTypeClick (type, e) {
    if( this.trackType == type ){
      return false;
    } else {
      let elem = $(e.target).parent().siblings(".one-peach-list-car").children('fa');
      if(elem.hasClass('fa-angle-double-right')){
        elem.addClass('fa-angle-double-left').removeClass('fa-angle-double-right');
        elem.parent().css({'boxShadow' : 'none' , 'width' : '300px' , 'left' : '0'}).find(".list-inline>li").css('width', '50%');
        elem.parent().find('.list-inline>li:nth-child(n+3)').hide();
      }
      this.stopSetInterval();
      this.isLoading = false;
      this.trackType = type;
      this.trackDeviceType = '0';
      this.clearAllLabel();
      this.carRealInfo = [];
      this.loadDataIndex = 1;
      this.lastRegionAreaOverlay = '';
      $('#pathDate').parent().hide();
      if(this.mapvLayer){
        this.mapvLayer.destroy();
      }
      if (type === 'history') {
        this.nullCarDataContent = '暂无数据';
        $('#pathDate').parent().show().siblings(".one-peach-list-car-body").css("top","104px");
      } else {
        $('#pathDate').parent().hide().siblings(".one-peach-list-car-body").css("top","70px");
        this.clearLushuData();
        this.getCarRealPoint();
      }
    }
  }
  /**
   *站点搜索
   */
  siteNameFocus (e) {
    this.activeSiteCode = '';
    if ( e.target.value ) {
      this.getCarSearchData(e.target);
    }else {
      this.carSearchArr = [];
    }
  }
  getCarSearchData (elem) {
    $(elem).siblings('.one-peach-dropdown-menu').show().prev().show();
    $(".one-map-marker-site-hint").removeClass("one-map-marker-site-hint");
    if ( this.carSearchCode ) {
      this.isLoading = true;
      this.slagService.getCarSearchData( this.carSearchCode).subscribe(
        result => this.responseUtil.success(result, this.progressSiteSearch),
        message => this.responseUtil.error(message)
      );
    }else {
      this.carSearchArr = [];
    }
  }
  private progressSiteSearch = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showSiteSearch(result.data);
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  showSiteSearch (data) {
    if ( data && data.siteList && data.siteList.length > 0 ) {
      this.activeSiteCode = data.siteList[0].deviceCode;
      this.carSearchArr = data.siteList;
    }
  }
  selectSearchSite (searchData) {
    const point = new BMap.Point(searchData.Longitude, searchData.Latitude);
    this.carSearchCode = searchData.deviceName;
    this.activeSiteCode = searchData.deviceCode;
    this.carSearchArr = [];
    this.map.centerAndZoom(point, this.map.getZoom());
    this.carSiteClick(searchData);
  }
  /**
   *上下键(暂定)
   */
  keyUpOrDown (e) {
    let activeIndex = 0;
    const activeSelectSite = $(e.target).siblings('.one-peach-dropdown-menu').children('.active');
    if ( activeSelectSite.length ) {
      activeIndex = activeSelectSite.index();
    }
    if ( e.keyCode === 38) {
      activeIndex--;
      if ( activeIndex < 0) {
        return false;
      }else {
        this.activeSiteCode = this.carSearchArr[activeIndex].deviceCode;
        let selfHeight = activeSelectSite.height()+6;
        let parentScrollTop = activeSelectSite.parent().scrollTop();
        $(activeSelectSite).parent().scrollTop(parentScrollTop-selfHeight);
      }
    }else if ( e.keyCode === 40 ) {
      activeIndex++;
      if ( activeIndex < this.carSearchArr.length ) {
        this.activeSiteCode = this.carSearchArr[activeIndex].deviceCode;
        let selfHeight = activeSelectSite.height()+6;
        let parentScrollTop = activeSelectSite.parent().scrollTop();
        $(activeSelectSite).parent().scrollTop(parentScrollTop+selfHeight);
      }
    }else if ( e.keyCode === 13 ) {
      if (activeIndex < this.carSearchArr.length && activeIndex >= 0) {
        const activeSelectData = this.carSearchArr[activeIndex];
        const point = new BMap.Point(activeSelectData.lng, activeSelectData.lat);
        this.carSearchCode = activeSelectData.deviceName;
        // $("#"+activeSelectData.deviceCode).parent().addClass("one-map-marker-site-hint").siblings().removeClass("one-map-marker-site-hint");
        this.map.centerAndZoom(point, this.map.getZoom());
        this.carSiteClick(activeSelectData);
        this.carSearchArr = [];
        this.activeSiteCode = '';
      }
    }
  }
  /**
   *收缩详情
   */
  shrinkSiteDetail (e) {
    const siteDetailHeight = $(e.target).parents('.one-peach-site-detail').height();
    if( $(e.target).hasClass('one-peach-site-toggle-large')){
      $(e.target).animate({
        left: 0
      }, 500, () => {
        $(e.target).removeClass('one-peach-site-toggle-large').addClass('one-peach-site-toggle').parents('.one-peach-site-detail').animate({
          right: '20px',
          bottom: '10px'
        }, 1000);
        $(e.target).parents('.one-peach-site-detail').siblings('.one-peach-factorLegend').animate({
          right: '330px'
        }, 1000);
      });
    } else {
      $(e.target).parents('.one-peach-site-detail').animate({
        right: '-300px',
        bottom: siteDetailHeight - 64 + 'px'
      }, 1000, () => {
        $(e.target).removeClass('one-peach-site-toggle').addClass('one-peach-site-toggle-large').animate({
          left: '-74px'
        }, 500);
      });
      $(e.target).parents('.one-peach-site-detail').siblings('.one-peach-factorLegend').animate({
        right: '20px'
      }, 1000);
    }
  }

  /**
   *地图缩放一个级别
   */
  zoomIn () {
    this.map.zoomIn();
  }
  zoomOut () {
    this.map.zoomOut();
  }
  /**
   *车辆类型
   */
  getCarType () {
    this.slagService.getCarType().subscribe(
      result => this.responseUtil.success(result, this.progressCarType),
      message => this.responseUtil.error(message)
    );
  }
  private progressCarType = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showCarType(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  showCarType (data) {
    if ( data && data.length ) {
      this.carTypeArr = data;
      this.getCarTypeNum();
    }
  }
  /**
   *车辆类型点击事件
   */
  carTypeClick(deviceCode){
    this.deviceType = deviceCode;
    this.loadDataIndex = 1;
    this.getCarRealPoint();
    this.clearAllLabel();
  }
  /**
   *路况
   */
  trafficControl(){
    this.trafficCtrl = new BMapLib.TrafficControl();
    this.map.addControl(this.trafficCtrl);
  }
  trafficBtnClick(){
    if(this.isTraffic){
      this.isTraffic = false;
      this.trafficCtrl.hideTraffic();
    }else{
      this.isTraffic = true;
      this.trafficCtrl.showTraffic();
    }
  }
  refreshTraffic () {
    if(this.isTraffic){
      this.trafficCtrl.showTraffic();
    }
  }
  /**
   *行政区划
   */
  getRegionData () {
    this.slagService.getRegionsTreeByRegion().subscribe(
      result => this.responseUtil.success(result, this.progressRegionData),
      message => this.responseUtil.error(message)
    );
  }
  private progressRegionData = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showRegionData(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  showRegionData (data) {
    this.regionDataArr = data.children;
    this.initRegionTree(data);
  }
  /**
   *行政区划树
   */
  initRegionTree(menus) {
    // 初始化菜单树
    let setting = {
      callback: {
        onClick: this.carRegionClick
      }
    };

    // 把树放进页面
    this.treeObj = $.fn.zTree.init($("#carRegionTree"), setting, menus);

  }
  carRegionClick = (event, treeId, treeNode) =>{
    if(treeNode.id == this.regionCode){
      this.regionCode = '';
      let selectedArray:Array<object> = this.treeObj.getSelectedNodes();
      if (selectedArray.length>0) {
        this.treeObj.cancelSelectedNode(selectedArray[0]);
      }
    }else{
      this.regionCode = treeNode.id ;
    }
    this.clearAllLabel();
    this.loadDataIndex = 1;
    this.getCarRealPoint();
  };
  /**
   *车辆状态
   */
  getCarStatus () {
    this.slagService.getCarStatus().subscribe(
      result => this.responseUtil.success(result, this.progressCarStatus),
      message => this.responseUtil.error(message)
    );
  }
  private progressCarStatus = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showCarStatus(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  showCarStatus (data) {
    if ( data && data.length ) {
      this.carStatusArr = data;
    }
  }
  /**
   *车辆状态点击事件
   */
  carStatusClick(statusCode){
    this.clearAllLabel();
    if ( statusCode == '-1' ) {
      this.deviceStatus = '';
    } else {
      this.deviceStatus = statusCode;
    }
    this.loadDataIndex = 1;
    this.getCarRealPoint();
  }
  /**
   *车辆数量
   */
  getCarTypeNum () {
    this.slagService.getCarTypeNum().subscribe(
      result => this.responseUtil.success(result, this.progressCarTypeNum),
      message => this.responseUtil.error(message)
    );
  }
  private progressCarTypeNum = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showCarTypeNum(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  showCarTypeNum (data) {
   this.siteCountChart(data);
  }
  /**
   *车辆实时信息
   */
  getCarRealPoint () {
    this.nullCarDataContent = '正在加载';
    this.stopSetInterval();
    this.isLoading = true;
    let deviceType = this.deviceType;
    let deviceStatus = this.deviceStatus;
    this.slagService.getCarRealPoint(deviceType, deviceStatus,this.regionCode).subscribe(
      result => this.responseUtil.success(result , () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          this.showCarRealPoint(result.data, deviceType, deviceStatus);
        } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
        this.isLoading = false;
      }),
      message => this.responseUtil.error(message)
    );
  }
  showCarRealPoint (data, deviceType, deviceStatus) {
    if(this.mapvLayer){
      this.mapvLayer.destroy();
    }
    if(deviceType == this.deviceType && deviceStatus == this.deviceStatus){
      if (data && data.siteList && data.siteList.length && this.trackType == 'real') {
        this.nullCarDataContent = '';
        this.carRealCacheInfo = data.siteList;
        // 标注
        // let partCarInfo: Array<any> = this.carRealInfo.slice((this.loadDataIndex-1)*this.loadDataNumber,this.loadDataIndex*this.loadDataNumber);
        // partCarInfo.forEach(( data, i ) => {
        //   if ( i == 0 ){
        //     this.map.centerAndZoom(new BMap.Point(data.lng,data.lat),this.map.getZoom());
        //   }
        //   this.mapCarLabel(data);
        // });
        // this.startSetInterval();

        let centerPoint: any ;
        if (data.centerSite && data.centerSite.lng && data.centerSite.lat ) {
          centerPoint = new BMap.Point( data.centerSite.lng , data.centerSite.lat );
        } else {
          centerPoint = new BMap.Point(this.carRealCacheInfo[0].lng,this.carRealCacheInfo[0].lat);
        }

        //  mapv
        this.carRealInfo = this.carRealCacheInfo.slice((this.loadDataIndex-1)*this.loadDataNumber,this.loadDataIndex*this.loadDataNumber);
        this.startSetInterval();
        this.map.centerAndZoom( centerPoint ,this.map.getZoom());

        //mapv
        this.mapvLoad();
        // //  聚合
        // let i = 0,pt,markers: Array<any> = [];
        // let myIcon = new BMap.Icon("assets/themes/peach/peachImg/icon-slag.png", new BMap.Size(32,32));
        // this.carRealInfo.forEach(( data, i ) => {
        //   pt = new BMap.Point(data.lng, data.lat);
        //   markers.push(new BMap.Marker(pt,{icon:myIcon}));
        // });
        // //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
        // const markerClusterer = new BMapLib.MarkerClusterer(this.map, {markers:markers});
        // console.log(markerClusterer.getGridSize());
        // console.log(markerClusterer.getStyles());
        // markerClusterer.setGridSize(120);
        // console.log(markerClusterer.getGridSize());
      }else{
        this.carRealInfo = [];
        this.nullCarDataContent = '暂无数据'
      }
    }
  }
  /**
   * mapv
   * */
  mapvLoad(){
    let img = new Image();
    img.src = '../../../../../assets/v1/css/peach/peachImg/icon-slag.png';
    let dataArr: Array<any> = [];
    this.carRealCacheInfo.forEach(( data, i ) => {
      dataArr.push({
        geometry: {
          type: 'Point',
          coordinates: [data.lng,data.lat]
        },
        detail : data,
        icon : img
      })
    });
    if(this.mapvLayer){
      this.mapvLayer.destroy();
    }
    let mapvDataSet = new mapv.DataSet(dataArr);
    let options = {
      methods: {
        click: (item) => {
          if(item){
            this.carSiteClick(item.detail);
          }
        },
        mousemove: (item) => {
          if(item){
            this.map.setDefaultCursor('pointer');
          }else{
            this.map.setDefaultCursor('default');
          }
        }
      },
      width: 32, // 规定图像的宽度
      height: 32, // 规定图像的高度
      // size: 5,
      draw: 'icon'
    };
    this.mapvLayer = new mapv.baiduMapLayer(this.map, mapvDataSet, options);
  }
  /**
  * 分批次加载数据
  * */
  startSetInterval = ()=> {
  this.loadSetInterval = setInterval(()=>{
      this.loadDataIndex++;
      let loadArr = this.carRealCacheInfo.slice((this.loadDataIndex-1)*this.loadDataNumber,this.loadDataIndex*this.loadDataNumber);
      if(loadArr.length>0){
        this.carRealInfo.concat(loadArr);
      }else{
        this.map.centerAndZoom(this.map.getCenter(), this.map.getZoom());
        this.stopSetInterval();
      }
    },this.loadDataTime)
  };
  stopSetInterval = ()=> {
    this.loadDataIndex = 1;
    clearInterval(this.loadSetInterval);
  };
  /**
   *车辆弹窗详细信息
   */
  carSiteHtml = (dataObj) => {
    return `
    <div class="one-peach-info">
      <div class="one-peach-info-header">
        <span>${dataObj.deviceName}</span>
      </div>  
      <div class="one-peach-info-body">
         <ul class="list-unstyled">
            <li>
              <div>车牌号：${dataObj.carCode}</div>
            </li>
            <li>
              <div>所属公司：${dataObj.companyName}</div>
            </li>
            <li>
              <div>车辆状态：${dataObj.deviceStatus}</div>  
            </li>
          </ul>  
        </div>
      </div>
    </div>
    `;
  };
  /**
   *车辆标注点击事件
   */
  carSiteClick = (dataObj) =>{
    let siteDataHtml = this.carSiteHtml(dataObj);
    let offset = new BMap.Size(18, 16);
    if(this.lastInfo){
      this.lastInfo.close();
    }
    let infoBox = new BMapLib.InfoBox(this.map,siteDataHtml,{
      boxStyle:{
        background:"#fff",
        width: "360px"
      },
      offset: offset,
      closeIconMargin: "13px 7px 0 0",
      enableAutoPan: true,
      align: INFOBOX_AT_TOP,
      closeIconUrl:"../../../../../../assets/imgs/ico-close.png"
    });
    this.lastInfo = infoBox;
    let point = new BMap.Point(dataObj.lng, dataObj.lat);
    infoBox.open(point);
  };
  /**
   *车辆实时信息列表点击事件
   */
  carRealListList(carDetail){
    const point = new BMap.Point(carDetail.lng, carDetail.lat);
    this.map.centerAndZoom(point,this.map.getZoom());
    this.carSiteClick(carDetail);
  }
  /**
   * 车辆标注
   */
  mapCarLabel(dataObj) {
    // let plat = -0.002035 + 0.0069;
    // let plng = 0.00486 + 0.0080;
    const point = new BMap.Point(dataObj.lng, dataObj.lat);
    let size;
    size = [32, 32];
      const myLabel = new BMap.Label(`
      <span id = '${dataObj.deviceCode}' class ='${dataObj.pointType} labelData ' 
      style=' color: #fff ;display:  inline-block;margin-left: -3px;'>
      </span> `,    // 为lable填写内容
      {
        offset: new BMap.Size(-size[0] / 2, -size[1] / 2),                     // label的偏移量，为了让label的中心显示在点上
        position: point
      });                                 // label的位置
    myLabel.setStyle({                                   // 给label设置样式，任意的CSS都是可以的
      maxWidth: size[0] + 'px',
      width: size[0] + 'px',  // 宽
      display: 'inline-block',
      fontSize: '14px',               // 字号
      border: '0',                    // 边
      height: size[1] + 'px',                 // 高度
      background: 'url(../../../../../assets/v1/css/peach/peachImg/icon-slag.png) no-repeat',    // 背景图片
      cursor: 'pointer'
    });
    let title = '';
    title = dataObj.deviceName;
    myLabel.setTitle(title);               // 为label添加鼠标提示
    this.map.addOverlay(myLabel);
  }
  /**
   *框选区域站点信息
   */
  getCarHistoryPoint () {
    this.nullCarDataContent = '正在加载';
    let arrPoints: Array<any> = [];
    const latSets: Array<any> = [];
    const lngSets: Array<any> = [];
    if (this.lastRegionAreaOverlay) {
      arrPoints = this.lastRegionAreaOverlay.getPath();
      arrPoints.forEach((data, i) => {
        latSets.push(data.lat);
        lngSets.push(data.lng);
      });
    }
    let trackSelectTime = this.trackSearchDate.split('至');
    const obj = {
      latSets: latSets.join(','),
      lngSets: lngSets.join(','),
      deviceType: this.deviceType,
      deviceStatus: this.deviceStatus,
      regionCode: this.regionCode,
      startTime: moment($.trim(trackSelectTime[0])).format('YYYY-MM-DD HH:mm:00'),
      endTime: moment(trackSelectTime[1]).format('YYYY-MM-DD HH:mm:00')
    };
    this.stopSetInterval();
    this.isLoading = true;
    this.slagService.getCarHistoryPoint(obj).subscribe(
      result => this.responseUtil.success(result, this.progressCarHistoryPoint),
      message => this.responseUtil.error(message)
    );
  }
  private progressCarHistoryPoint = (result: MsgResult) =>{
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showCarHistoryPoint(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
    this.isLoading = false;
  }
  showCarHistoryPoint (data) {
    if(this.mapvLayer){
      this.mapvLayer.destroy();
    }
    if (data && data.length > 0  && this.trackType == 'history') {
      // 标注
      // this.carRealInfo = data;
      // console.log(this.carRealInfo);
      // this.carRealInfo.forEach(( val) => {
      //   this.mapCarLabel(val);
      // });

      //  mapv
      this.carRealCacheInfo = data;
      this.carRealInfo = this.carRealCacheInfo.slice((this.loadDataIndex-1)*this.loadDataNumber,this.loadDataIndex*this.loadDataNumber);
      this.startSetInterval();
      this.map.centerAndZoom(new BMap.Point(this.carRealCacheInfo[0].lng,this.carRealCacheInfo[0].lat),this.map.getZoom());
      this.mapvLoad();
      this.nullCarDataContent = ''
    }else{
      // this.clearAllLabel();
      // this.map.addOverlay(this.lastRegionAreaOverlay);
      if(this.mapvLayer){
        this.mapvLayer.destroy();
      }
      this.carRealInfo = [];
      this.nullCarDataContent = '暂无数据'
    }
  }
  /**
   *框选区域
   */
  regionAreaClick () {
    if (this.lastRegionAreaOverlay) {
      this.map.removeOverlay(this.lastRegionAreaOverlay);
      this.lastRegionAreaOverlay = '';
      this.map.clearOverlays();
      this.carRealInfo = [];
    }
    const myDrawingManagerObject = new BMapLib.DrawingManager(this.map, {
      isOpen: true,
      polygonOptions: {
        fillColor: '#eea77c',
        strokeColor: '#eea77c',
        strokeWidth: 2,
        fillOpacity: 0.28
      }
    });
    myDrawingManagerObject.setDrawingMode(BMAP_DRAWING_POLYGON);
    myDrawingManagerObject.open();
    myDrawingManagerObject.addEventListener('polygoncomplete', (e, overlay) =>{
      this.lastRegionAreaOverlay = overlay;
      this.getCarHistoryPoint();
    });
  }
  /**
   *收缩车辆列表
   */
  shrinkCarList ( e ) {
    const elem = $( e.target );
    if ( elem.hasClass('fa-angle-double-left') ){
      let bodyWidth = '20%';
      let companyWidth = '50%';
      let firstWidth = '30%';
      if ( this.trackType === 'real' ){
        bodyWidth = '10%';
        companyWidth = '40%';
        firstWidth = '17%';
      }
      elem.removeClass(' fa-angle-double-left ').addClass(' fa-angle-double-right ');
      elem.parent().css({'boxShadow' : '0 2px 10px rgba(0,0,0,.5)' , 'width' : '940px' , 'left' : '-640px'}).find(".list-inline>li").css('width', bodyWidth);
      elem.parent().find('.list-inline>li:nth-child(n+3)').show();
      elem.parent().find('.list-inline>li:first-child').css('width', firstWidth);
      elem.parent().find('.list-inline>li.large').css('width', companyWidth);
      elem.parent().find('.list-inline>li:nth-child(n+3)').show();
    } else {
      elem.addClass('fa-angle-double-left ').removeClass(' fa-angle-double-right');
      elem.parent().css({'boxShadow' : 'none' , 'width' : '300px' , 'left' : '0'}).find(".list-inline>li").css('width', '50%');
      elem.parent().find('.list-inline>li:nth-child(n+3)').hide();
    }
  }
  /**
   *历史数据中的车辆点击事件
   */
  historyDataClick(track, e){
    if(track.siteStatus != '1111'){
      return false;
    }else{
      this.lushuClickElem = e.target;
      if ( !$( e.target).siblings('input').is(':checked')){
        this.lushuOverlays.push(track.deviceCode);
        this.trackDeviceCode = track.deviceCode;
        this.getHistoryGPSData(track.deviceCode);
      }else{
        if (this.lushuOverlays.indexOf(track.deviceCode) !== -1 ){
          const lushuIndex = this.lushuOverlays.indexOf(track.deviceCode);
          const clearLushu = this.lushuData[lushuIndex];
          this.map.removeOverlay(this.lushuLine[lushuIndex]);
          this.lushuOverlays.splice(lushuIndex, 1);
          this.lushuData.splice(lushuIndex, 1);
          this.lushuLine.splice(lushuIndex, 1);
          if($( e.target).parent().siblings('.fa').hasClass('fa-pause')){
            $( e.target).parent().siblings('.fa').removeClass('fa-pause').addClass('fa-play');
            clearLushu.stop();
            this.deleteLushuIcon();
          }
        }
      }
    }
  }
  /**
   *显示巡检轨迹
   */
  getHistoryGPSData (deviceCode) {
    this.isLoading = true;
    let trackSelectTime = this.trackSearchDate.split('至');
    const obj = {
      startTime : moment($.trim(trackSelectTime[0])).format('YYYY-MM-DD HH:mm:00'),
      endTime : moment(trackSelectTime[1]).format('YYYY-MM-DD HH:mm:00'),
      deviceCode : deviceCode
    };
    this.slagService.getHistoryGPSData(obj).subscribe(
      result => this.responseUtil.success(result, this.progressHistoryGps),
      message => this.responseUtil.error(message)
    )
  }
  private progressHistoryGps = (result: MsgResult) =>{
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.showHistoryGpsData(result.data);
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  showHistoryGpsData = (data) => {
    if( data && data.hasOwnProperty('trackList') && data.trackList.length > 0 ) {
      const trackPoint = data.trackList;
      const arrPoints = [];
      // let plat = -0.002035 + 0.0069;
      // let plng = 0.00486 + 0.0080;
      trackPoint.forEach( (point , i) =>  {
        if(!isNaN(point.lng)){
          point.lng = Number(point.lng);
        }
        if(!isNaN(point.lat)){
          point.lat = Number(point.lat);
        }
        arrPoints.push(new BMap.Point(point.lng, point.lat));
      });
      this.lushuPath(arrPoints, '#48ab5d');
    }else{
      this.lushuOverlays.splice(-1,1);
      $(this.lushuClickElem).siblings('input')[0].checked = false;
      this.dialogService.info('暂无巡检路线');
    }
  };
  /**
   *路书路线显示
   */
  lushuPath (arrPois, color) {
    let lushu;
    const polyLine  = new BMap.Polyline(arrPois, {strokeColor: color});
    this.map.addOverlay(polyLine);   /*颜色*/
    this.map.setViewport(arrPois);   /*调整视野*/

    lushu = new BMapLib.LuShu(this.map, arrPois, {
      // defaultContent:' ',// 提示框的默认内容
      // autoView:true,// 是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
      icon  : new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52, 26), { anchor : new BMap.Size(27, 13)}),
      speed: 2000,
      enableRotation: true, //  是否设置marker随着道路的走向进行旋转
      landmarkPois: [  //  数组必须存在
        //  特殊点设置
        // {lng:116.402046,lat:39.913928,html:'aa',pauseTime:2},
        //  lng:116.376683,lat:39.913282,html:'加油站',pauseTime:2},
        // {lng:116.378477,lat:39.954493,html:'高速公路收费',pauseTime:10},
        // {lng:116.303499,lat:40.063862,html:'肯德基早餐',pauseTime:10}
      ]
    });
    this.lushuLine.push(polyLine);
    this.lushuData.push(lushu);
  }
  /**
   * 巡检轨迹回放的点击事件
   */
  trackSportClick(e, track) {
    const lushuIndex = this.lushuOverlays.indexOf(track.deviceCode);
    const lushu = this.lushuData[lushuIndex];
    if ( $(e.target).siblings('label').children('input:checked').length && $(e.target).hasClass('fa-play')) {
      let startElem = $(e.target).parents('.one-peach-list-car-body').find('.fa-pause');
      if ( startElem.length > 0 ) {
        startElem.removeClass('fa-pause').addClass('fa-play');
        const clearIndex = this.lushuOverlays.indexOf(startElem.attr('id'));
        const clearLushu = this.lushuData[clearIndex];
        clearLushu.stop();
        this.deleteLushuIcon();
      }
      if (lushu) {
        $(e.target).removeClass('fa-play').addClass('fa-pause');
        lushu.start();
      }
      this.map.getOverlays().forEach((overlay)=>{
        if(overlay.getIcon){
          this.lushuSpotrIcon.push(overlay);
        }
      })
    }else if ( $(e.target).siblings('label').children('input:checked').length && $(e.target).hasClass('fa-pause')){
      $(e.target).removeClass('fa-pause').addClass('fa-play');
      lushu.stop();
      this.deleteLushuIcon();
    }
  }
}
